package com.tieto.poll.model;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.IteratorUtils;

import com.tieto.poll.model.Poll;
import com.tieto.repository.EntityFactory;
import com.tieto.user.model.User;
import com.tieto.user.model.UserFactory;
import com.tieto.user.repository.UserRepository;

public class PollFactory implements EntityFactory<Poll, Long> {

    private UserRepository userRepository;

    public PollFactory(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public List<Poll> getEntities(int count) {
        User user = createOrGetUser();
        List<Poll> entities = new ArrayList<Poll>();
        for (int i = 0; i < count; i++) {
            Poll poll = new Poll("poll name " + i);
            poll.setOwner(user);
            poll.setQuestions(new ArrayList<Question>());
            for (int j = 0; j < count; j++) {
                Question question = new Question();
                question.setPoll(poll);
                poll.getQuestions().add(question);
            }
            entities.add(poll);
        }
        return entities;
    }

    private User createOrGetUser() {
        @SuppressWarnings("unchecked")
        List<User> users = IteratorUtils.toList(userRepository.findAll().iterator());
        User user;
        if (!users.isEmpty()) {
            user = users.get(0);
        }else {
            UserFactory userFactory = new UserFactory();
            user = userFactory.getEntities(1).get(0);
            userRepository.save(user);
        }
        return user;
    }

    @Override
    public Poll getUpdatedEntity(Poll entity) {
        // cannot update name, since it is the the natural id
        Poll poll = new Poll(entity.getName());
        poll.setOwner(entity.getOwner());
        poll.setQuestions(entity.getQuestions());
        return poll;
    }
}
